import { Message, MessageRole, MessageType, AIModelAdapter } from '../types'
import { Ollama } from 'ollama'

// Ollama模型适配器
export class OllamaAdapter extends AIModelAdapter {
  constructor(config) {
    super(config)
    this.apiEndpoint = config.apiEndpoint || 'http://localhost:11434'
    this.modelName = config.modelName || 'llama2'
    this.systemPrompt = config.systemPrompt || ''
    this.messageHistory = []
    this.ollama = new Ollama({
      host: this.apiEndpoint
    })
  }

  async sendMessage(message, onUpdate) {
    try {
      if (!this.apiEndpoint) {
        throw new Error('未配置Ollama服务地址')
      }

      // 如果消息历史为空且存在系统提示词，则添加系统提示词作为第一条消息
      if (this.messageHistory.length === 0 && this.systemPrompt) {
        this.messageHistory.push({
          role: 'system',
          content: this.systemPrompt
        })
      }

      // 添加当前消息到历史记录
      this.messageHistory.push({
        role: 'user',
        content: message.content
      })

      let accumulatedContent = ''
      let typingStarted = false

      // 使用stream方式获取响应
      const response = await this.ollama.chat({
        model: this.modelName,
        messages: this.messageHistory,
        stream: true
      })

      for await (const chunk of response) {
        if (chunk.message?.content) {
          if (!typingStarted) {
            // 显示打字机效果开始的状态
            if (onUpdate) {
              onUpdate(new Message({
                role: MessageRole.ASSISTANT,
                type: MessageType.TEXT,
                content: '',
                metadata: { thinking: false, typing: true }
              }))
            }
            typingStarted = true
          }
          
          accumulatedContent += chunk.message.content
          if (onUpdate) {
            onUpdate(new Message({
              role: MessageRole.ASSISTANT,
              type: MessageType.TEXT,
              content: accumulatedContent,
              metadata: { typing: true }
            }))
          }
        }
      }

      // 添加AI响应到历史记录
      this.messageHistory.push({
        role: 'assistant',
        content: accumulatedContent
      })

      return new Message({
        role: MessageRole.ASSISTANT,
        type: MessageType.TEXT,
        content: accumulatedContent
      })
    } catch (error) {
      console.error('Ollama API调用失败:', error)
      if (error.message.includes('Failed to fetch')) {
        throw new Error('无法连接到Ollama服务，请确保服务已启动')
      }
      throw error
    }
  }
}
